using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using S.M.SmartMedical.API.Read.Application.Query;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure;

namespace S.M.SmartMedical.API.Read.Application.Handler;

/// <summary>
/// 获取医疗项目查询处理器
/// </summary>
public class GetMedicalProjectsHandler : IRequestHandler<GetMedicalProjectsQuery, APIResult<List<MedicalProjectDto>>>
{
    private readonly MyDbContext _context;
    private readonly IMapper _mapper;

    public GetMedicalProjectsHandler(MyDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    /// <summary>
    /// 处理获取医疗项目查询
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <param name="cancellationToken">取消令牌</param>
    /// <returns>医疗项目列表</returns>
    public async Task<APIResult<List<MedicalProjectDto>>> Handle(GetMedicalProjectsQuery request, CancellationToken cancellationToken)
    {
        try
        {
            // 构建查询
            var query = _context.MedicalProjects
                .Where(p => !p.IsDeleted && p.HospitalAreaId == request.HospitalAreaId);

            // 过滤启用状态
            if (request.OnlyEnabled)
            {
                query = query.Where(p => p.IsEnabled);
            }

            // 过滤项目类别
            if (request.Category.HasValue)
            {
                query = query.Where(p => p.Category == request.Category.Value);
            }

            // 搜索关键词过滤
            if (!string.IsNullOrWhiteSpace(request.SearchKeyword))
            {
                var keyword = request.SearchKeyword.Trim();
                query = query.Where(p => 
                    p.Name.Contains(keyword) || 
                    (p.Description != null && p.Description.Contains(keyword)) ||
                    (p.Tags != null && p.Tags.Contains(keyword)) ||
                    p.Code.Contains(keyword));
            }

            // 按排序顺序和名称排序
            query = query.OrderBy(p => p.SortOrder).ThenBy(p => p.Name);

            // 执行查询
            var projects = await query.ToListAsync(cancellationToken);

            // 映射到DTO
            var projectDtos = _mapper.Map<List<MedicalProjectDto>>(projects);

            return new APIResult<List<MedicalProjectDto>>
            {
                Code = APIEnum.OK,
                Message = "获取医疗项目列表成功",
                Data = projectDtos
            };
        }
        catch (Exception ex)
        {
            return new APIResult<List<MedicalProjectDto>>
            {
                Code = APIEnum.Fail,
                Message = $"获取医疗项目列表失败：{ex.Message}",
                Data = new List<MedicalProjectDto>()
            };
        }
    }
}